package com.baosight.risk.web.jlta;

import com.baosight.risk.api.jlta.JltaResourceService;
import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.file.FileManager;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.service.jlta.entity.JltaResource;
import com.baosight.risk.service.jlta.entity.JltaTeam;
import com.baosight.risk.service.jlta.vo.JltaResourceVO;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(value = "资源共享", description = "资源共享", produces = MediaType.APPLICATION_JSON)
@Slf4j
@RestController
@RequestMapping("/jlta/resource")
public class JltaResourceController extends BaseController {

    @Autowired
    private JltaResourceService jltaResourceService;

    @Autowired
    private XtdcAttachService xtdcAttachService;

    @Autowired
    private FileManager fileManager;

    @ApiOperation("获取我的资源")
    @GetMapping("selfResourceList")
    public AjaxResult selfResourceList(JltaResource jltaResource) {
        startPage();
        return getResultPage(jltaResourceService.selectSelfResourceList(jltaResource));
    }

    @ApiOperation("获取共享的资源")
    @GetMapping("sharedResourceList")
    public AjaxResult sharedResourceList() {
        String userId = getUser().getId();
        startPage();
        return getResultPage(jltaResourceService.selectSharedResourceList(userId));
    }

    @ApiOperation("获取资源中的附件")
    @GetMapping("fileList")
    public AjaxResult fileList(String id) {
        return AjaxResult.success("操作成功", jltaResourceService.selectFileList(id));
    }

    @ApiOperation("新增资源")
    @PostMapping("addResource")
    public AjaxResult addResource(@RequestBody JltaResourceVO vo) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        String id = UUID.randomUUID().toString();
        Date now = new Date();
        JltaResource jltaResource = new JltaResource();
        jltaResource.setId(id);
        jltaResource.setResourceCode(id);
        jltaResource.setResourceName(vo.getResourceName());
        jltaResource.setResourceDesc(vo.getResourceDesc());
        jltaResource.setCreaterId(sysUser.getId());
        jltaResource.setCreaterName(sysUser.getUserDesc());
        jltaResource.setCompId(sysUser.getExt1());
        jltaResource.setCompCode(sysUser.getExt1());
        jltaResource.setCompName(sysUser.getExt2());
        jltaResource.setCreateBy(userCode);
        jltaResource.setCreateTime(now);
        jltaResource.setStatus("0");
        Integer result = jltaResourceService.addResource(jltaResource);
        if (result == 0) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    @ApiOperation("新增资源带附件")
    @PostMapping("uploadResource")
    public AjaxResult uploadResource(HttpServletRequest request) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        //转换request
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        //获取页面传参
        String resourceName = multipartRequest.getParameter("resourceName");
        String resourceDesc = multipartRequest.getParameter("resourceDesc");
        String businessCode = multipartRequest.getParameter("businessCode");
        String teamId = multipartRequest.getParameter("teamId");

        String resourceCode = UUID.randomUUID().toString();
        Date now = new Date();
        List<Map<String, Object>> list = new ArrayList<>();
        //获取附件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        try {
            for (String key : fileMap.keySet()) {
                MultipartFile multipartFile = fileMap.get(key);
                InputStream inputStream = multipartFile.getInputStream();
                String filename = multipartFile.getOriginalFilename();
                long fileSize = multipartFile.getSize();

                FileManager.Config config = fileManager.getConfig();
                config.setInputStream(inputStream);
                config.setBusinessCode(businessCode);
                config.setFilename(filename);

                //生成目录
                String dir = fileManager.generateDir(config);
                String filepath = dir + "/" + filename;
                //保存文件到磁盘
                multipartFile.transferTo(new File(filepath));
                Map<String, Object> map = new HashMap<>();
                map.put("filename", filename);
                map.put("fileSize", fileSize);
                map.put("filepath", filepath);
                list.add(map);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("任务中心-资源共享：上传附件失败！");
            return AjaxResult.error();
        }


        for (Map<String, Object> map : list) {
            String filename = (String) map.get("filename");
            long fileSize = (long) map.get("fileSize");
            String filepath = (String) map.get("filepath");

            String fileType = "file";
            int indx = filename.lastIndexOf(".");
            if (indx > 0 && indx < filename.length() - 1) {
                fileType = filename.substring(indx + 1).toLowerCase();
            }
            //存入数据库==注意teamId
            XtdcAttach attach = (XtdcAttach) BeanUtils.initBean(new XtdcAttach());
            attach.setFileName(filename);
            attach.setFilePath(filepath);
            attach.setFileSize(fileSize);
            attach.setFileType(fileType);
            attach.setFolderId("1");
            xtdcAttachService.insert(attach);

            String id = UUID.randomUUID().toString();
            JltaResource jltaResource = new JltaResource();
            jltaResource.setId(id);
            jltaResource.setResourceCode(resourceCode);
            jltaResource.setResourceName(resourceName);
            jltaResource.setResourceDesc(resourceDesc);
            jltaResource.setFileId(attach.getId());
            jltaResource.setCreaterId(sysUser.getId());
            jltaResource.setCreaterName(sysUser.getUserDesc());
            jltaResource.setCompId(sysUser.getExt1());
            jltaResource.setCompCode(sysUser.getExt1());
            jltaResource.setCompName(sysUser.getExt2());
            jltaResource.setCreateBy(userCode);
            jltaResource.setCreateTime(now);
            jltaResource.setStatus("0");
            jltaResourceService.addResource(jltaResource);
        }

        return AjaxResult.success();
    }

    @ApiOperation("删除资源")
        @PutMapping("deleteResource")
    public AjaxResult deleteResource(@RequestBody List<String> ids) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();
        for (String id : ids) {
            JltaResource jltaResource = new JltaResource();
            jltaResource.setId(id);
            jltaResource.setStatus("2");
            jltaResource.setUpdateBy(userCode);
            jltaResource.setUpdateTime(new Date());
            jltaResourceService.deleteResource(jltaResource);
        }
        return AjaxResult.success();
    }

    @ApiOperation("修改资源")
    @PostMapping("editResource")
    public AjaxResult editResource(@RequestBody JltaResourceVO vo) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        JltaResource jltaResource = new JltaResource();
        jltaResource.setId(vo.getId());
        jltaResource.setResourceName(vo.getResourceName());
        jltaResource.setResourceDesc(vo.getResourceDesc());
        jltaResource.setUpdateBy(userCode);
        jltaResource.setUpdateTime(new Date());
        Integer result = jltaResourceService.editResource(jltaResource);
        if (result > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("发布资源")
    @PutMapping("publishResource")
    public AjaxResult publishResource(@RequestBody List<String> ids) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();
        for (String id : ids) {
            JltaResource jltaResource = new JltaResource();
            jltaResource.setId(id);
            jltaResource.setStatus("1");
            jltaResource.setUpdateBy(userCode);
            jltaResource.setUpdateTime(new Date());
            jltaResourceService.deleteResource(jltaResource);
        }
        return AjaxResult.success();
    }

    @ApiOperation("根据团队获取资源")
    @GetMapping("getResourceByTeam")
    public AjaxResult getResourceByTeam(@RequestParam("teamId") String teamId) {
        List<JltaResource> resourceList = jltaResourceService.getResourceByTeam(teamId);
        return AjaxResult.success("成功", resourceList);
    }

}
